/**
 * Simple ExtJS 4 wrapper class for OpenLayers map. The actual map setup
 * logic is delegated to vvg.lib.ol.*; this class only acts as a thin wrapper
 * to allow the map component to be laid out using ExtJS 4.
 * 
 * Relies on:
 * - vvg.lib.ol.* to create actual OpenLayers component.
 * 
 * @author: King Lung Chiu
 */
(function(vvg){
   
   var app = vvg.app = vvg.app || {};
   var appMapViews = vvg.app.xMapViews = app.xMapViews || [];
   var credits = app.credits;
   var lib = vvg.lib;
   var VIZ_DATA_READY = lib.eventNames.VIZ_DATA_READY;
   var VIZ_DATA_FETCH_STARTED = lib.eventNames.VIZ_DATA_FETCH_STARTED;
   var VIZ_DATA_FETCH_COMPLETE = lib.eventNames.VIZ_DATA_FETCH_COMPLETE;

   var TOOLBAR_itemId = 'vvg_MapView_Toolbar';
   var MAP_CONTAINER_itemId = 'vvg_olMap_Container';
   var LON_FIELD_itemId = 'vvg_MapView_lonField';
   var LAT_FIELD_itemId = 'vvg_MapView_latField';

   var MAX_BUFFER_SIZE = 5; // TODO: get default max from lib.ol vizBufferMax
   var INIT_BUFFER_SIZE = MAX_BUFFER_SIZE;
   var INIT_START_YEAR = 2010;
   var INIT_END_YEAR = 2013;
   
   var lonLatFieldRegex = /-?\d+\.(?=\d+)/;
   var setMapLonLat = function (textfield){
      var lonField = textfield.ownerCt.getComponent(LON_FIELD_itemId);
      var latField = textfield.ownerCt.getComponent(LAT_FIELD_itemId);
      var map = textfield.ownerCt.ownerCt.vvg_appData.map;
      map.setCenter(new OpenLayers.LonLat(lonField.value, latField.value));
   }

   function bufferSliderLabel(bufferSize) {
      return ('Buffer Size ('+ bufferSize.toFixed(2) +' km)');
   }
   
   function datesSliderLabel(startYear, endYear) {
      return ('Filter Period ('+ startYear +'-'+ endYear+')');
   }

   function logSize(msg, size) {
      console.log(msg + ': ' + size.width + ' x ' + size.height);
   }
   
   Ext.define('VVG.view.MapView', {
      alias : 'widget.mapview'
      ,extend: 'Ext.container.Container'
//      ,extend: 'Ext.Component'
      ,layout: 'border'
      ,items: [{
         xtype: 'toolbar'
         ,region: 'north'
         ,itemId: TOOLBAR_itemId
         ,enableOverflow: true
         ,items: ['-',{
            iconCls: 'vvgMapControlHome'
            ,handler: function(button) {
               button.ownerCt.ownerCt.vvg_appData.map.vvg_panToHome();
            }
         }
         ,'-'
         ,{
            xtype: 'textfield'
            ,fieldLabel: 'Lon'
            ,itemId: LON_FIELD_itemId
            ,labelWidth: 30
            ,width: 175
            ,regex: lonLatFieldRegex
            ,listeners: {
               change: setMapLonLat
            }
         },' '
         ,{
            xtype: 'textfield'
            ,fieldLabel: 'Lat'
            ,itemId: LAT_FIELD_itemId
            ,labelWidth: 30
            ,width: 175
            ,regex: lonLatFieldRegex
            ,listeners: {
               change: setMapLonLat
            }
         },' '
         ,'-'
//         ,{
//            iconCls: 'vvgMapControlPan'
//            ,toggleGroup: 'mapcontrols'
//            ,text: 'Pan'
//            ,pressed: true
//         },{
//            iconCls: 'vvgMapControlSketch'
//            ,toggleGroup: 'mapcontrols'
//            ,text: 'Sketch'
//         }
//         ,'-',' '
         ,'->','-'
         ,{
            xtype: 'slider'
            ,fieldLabel: bufferSliderLabel(INIT_BUFFER_SIZE)
            ,labelClsExtra: 'vvg-MapControl-SliderLabel'
            ,labelWidth: 155  // use with accessibility theme
            ,width: 348       // use with accessibility theme
//            ,labelWidth: 105   // use with standard sized theme
//            ,width: 298        // use with standard sized theme
            ,useTips: false
            ,value: INIT_BUFFER_SIZE
            ,minValue: 0.1
            ,maxValue: MAX_BUFFER_SIZE
            ,increment: 0.1
            ,decimalPrecision: 1
            ,listeners: {
               change: function(slider, value) {
                  slider.setFieldLabel(bufferSliderLabel(value));
                  slider.ownerCt.ownerCt.vvg_appData.map.vvg_updateVizBuffer(
                     value, false);
               }
               ,changecomplete: function(slider, value) {
                  slider.ownerCt.ownerCt.vvg_appData.map.vvg_updateVizBuffer(
                     value, true);
               }
            }
         },' '
         ,'-',' '
         ,{
            xtype: 'multislider'
            ,fieldLabel: datesSliderLabel(INIT_START_YEAR, INIT_END_YEAR)
//            ,fieldLabel: 'Start Year (2012)'
            ,labelClsExtra: 'vvg-MapControl-SliderLabel'
            ,labelWidth: 180  // use with accessibility theme
            ,width: 373       // use with accessibility theme
//            ,labelWidth: 130   // use with standard sized theme
//            ,width: 323        // use with standard sized theme
            ,useTips: false
            ,minValue: 1960
            ,maxValue: 2013
            ,increment: 1
//            ,value: 2012
            ,values: [INIT_START_YEAR, INIT_END_YEAR]
            ,listeners: {
               change: function(slider) {
                  var year1 = slider.thumbs[0].value;
                  var year2 = slider.thumbs[1].value;
                  slider.setFieldLabel(datesSliderLabel(year1, year2));
                  slider.ownerCt.ownerCt.vvg_appData.map.vvg_updateVizDates(
                     year1.toString(), year2.toString(), false);
               }
               ,changecomplete: function(slider) {
                  slider.ownerCt.ownerCt.vvg_appData.map.vvg_updateVizDates(
                     slider.thumbs[0].value.toString()
                     ,slider.thumbs[1].value.toString()
                     ,true
                  );
               }
            }
//            ,listeners: {
//               change: function(slider, value) {
//                  slider.setFieldLabel('Start Year ('+ value +')');
//                  slider.ownerCt.ownerCt.vvg_appData.map.vvg_updateVizDates(
//                     value.toString(), '2013', false);
//               }
//               ,changecomplete: function(slider, value) {
//                  lib.log('MapView Start Year Slider change complete: '+ value)
//                  slider.ownerCt.ownerCt.vvg_appData.map.vvg_updateVizDates(
//                     value.toString(), '2013', true);
//               }
//            }
         },' ','-'
         ,{
            text: 'About'
            ,handler: function() {
               Ext.Msg.show({
                  title: credits.title
                  ,animateTarget: this.id
                  ,msg: credits.text
                  ,width: credits.width
               });
            }
         }
         ,'-']
      },{
         xtype: 'component'
         ,region: 'center'
         ,itemId: MAP_CONTAINER_itemId
      }]
      
      ,initComponent: function() {
         this.addEvents(VIZ_DATA_READY);
         this.addEvents(VIZ_DATA_FETCH_STARTED);
         this.addEvents(VIZ_DATA_FETCH_COMPLETE);
         
         this.callParent(arguments);
         appMapViews.push(this);
      }
      
      ,afterComponentLayout : function() {
         this.vvg_redrawMap();
         this.callParent(arguments);
         
//         var msg = 'afterComponentLayout ';
//         this.logSize(msg + ' pre parent', this.getSize());
//         this.logSize(msg + ' post parent', this.getSize());
      }
      
      /**
       * Container for holding custom properties.
       */
      ,vvg_appData: {
         map: null   // the internal OpenLayers map component
      }

      /**
       * Redraws the internal OpenLayers map. Call this when the component
       * is resized, so the map can display properly again.
       * 
       * Will create the actual OpenLayers map component if it doesn't
       * already exist.
       */
      ,vvg_redrawMap: function() {
         var self = this;
         var appData = self.vvg_appData;
         var map = appData.map;
         var mapDivId = self.getComponent(MAP_CONTAINER_itemId).getId();
         if(!map) {
            appData.map = lib.ol.createMap(
               mapDivId,
               lib.objFromKVPairs([
                  [VIZ_DATA_READY, function(vizData){
                     self.fireEvent(VIZ_DATA_READY, vizData);
                  }]
                  ,[VIZ_DATA_FETCH_STARTED, function(event){
                     self.fireEvent(VIZ_DATA_FETCH_STARTED, event);
                  }]
                  ,[VIZ_DATA_FETCH_COMPLETE, function(event){
                     self.fireEvent(VIZ_DATA_FETCH_COMPLETE, event);
                  }]
                  ,['moveend', function(event){
                     var center = event.object.getCenter();
                     var toolbar = self.getComponent(TOOLBAR_itemId);
                     var lonField = toolbar.getComponent(LON_FIELD_itemId);
                     var latField = toolbar.getComponent(LAT_FIELD_itemId);
                     lonField.setRawValue(center.lon);
                     latField.setRawValue(center.lat);
                  }]
               ])
            );
            appData.map.vvg_updateVizBuffer(INIT_BUFFER_SIZE, true);
            appData.map.vvg_updateVizDates(
               INIT_START_YEAR.toString(),INIT_END_YEAR.toString(), true
            );

         } else {
            map.vvg_redrawMap(mapDivId);
         }
      }

      ,vvg_selectBore: function(boreId) {
         this.vvg_appData.map.vvg_selectBore(boreId);
      }
      ,vvg_unselectBore: function(boreId) {
         this.vvg_appData.map.vvg_unselectBore(boreId);
      }
//      ,vvg_redrawMap: function() {
//         var self = this;
//         var appData = self.vvg_appData;
//         var map = appData.map;
//         if(!map) {
//            appData.map = lib.ol.createMap(
//               self.getId(),
//               lib.newObj(VIZ_DATA_READY, function(vizData) {
//                  self.fireEvent(VIZ_DATA_READY, vizData);
//               })
//            );
//         } else {
//            map.vvg_redrawMap(self.getId());
//         }
//      }
   });
   
}(window.vvg = window.vvg || {}));
